package middleware

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog"
	"io/ioutil"
	"shangke-device/internal/utils"
	"strings"
	"time"
)

func GinLogger(Lg *zerolog.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		ctx, traceId := utils.GetTraceID(c.Request.Context())
		c.Request = c.Request.WithContext(ctx)

		var params string
		if c.Request.Method == "GET" {
			params = c.Request.URL.RawQuery
		} else {
			body, _ := c.GetRawData()
			c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
			params = string(body)
			params = strings.Replace(params, "\r", "", -1)
			params = strings.Replace(params, "\n", "", -1)
		}

		c.Next()

		latency := time.Now().Sub(start)
		err := c.Errors.Last()
		if err == nil {
			Lg.Debug().Str("trace", traceId).Msgf("[%s] %d %s %s latency:%s params:%s ", c.Request.Method, c.Writer.Status(), c.Request.Proto, c.Request.URL.Path, latency, params)
		} else {
			Lg.Error().Str("trace", traceId).Msgf("[%s] %d %s %s latency:%s params:%s err:%s", c.Request.Method, c.Writer.Status(), c.Request.Proto, c.Request.URL.Path, latency, params, err.Error())
		}
	}
}
